<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../css/search.css">
    <script src="../js/cookie.js"></script>
    <script src="../js/ajax.js"></script>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .w {
            width: 1140px;
            margin: 0 auto;
        }

        .gradeList table {
            width: 100%;
            border-collapse: collapse;
            table-layout: fixed;
            text-align: center;
            line-height: 32px;
            font-size: 18px;
        }

        .gradeList table,
        .gradeList th,
        .gradeList td {
            border: 1px solid #333;
        }

        .pageBox {
            margin-top: 20px;
            display: flex;
            justify-content: center;
        }

        .pageBox>* {
            margin: 0 5px;
        }
    </style>
</head>

<body>
    <div class="box">
        <a href="./login.html">你好,请登录</a>
        <a href="./register.html">注册</a>
    </div>

    <div class="wrapAll w">
        <form class="search_bar" onsubmit="return false">
            <div class="searchBox">
                <input type="text" class="searchCon">
                <button class="searchBtn">搜索</button>
            </div>
            <div class="orderBox">
                <!-- 排序的列(column)名 (id,chinese,math,english,total) -->
                <div class="orderColBox">
                    <label>
                        学号
                        <input type="radio" checked name="orderCol" class="orderCol" value="id">
                    </label>
                    <label>
                        语文
                        <input type="radio" name="orderCol" class="orderCol" value="chinese">
                    </label>
                    <label>
                        数学
                        <input type="radio" name="orderCol" class="orderCol" value="math">
                    </label>
                    <label>
                        英语
                        <input type="radio" name="orderCol" class="orderCol" value="english">
                    </label>
                    <label>
                        总分
                        <input type="radio" name="orderCol" class="orderCol" value="total">
                    </label>
                </div>

                <!-- 排序的类型  升序 / 降序 -->
                <div class="orderTypeBox">
                    <label>
                        升序
                        <input type="radio" checked name="orderType" class="orderType" value="asc">
                    </label>
                    <label>
                        降序
                        <input type="radio" name="orderType" class="orderType" value="desc">
                    </label>
                </div>

                <div class="showNumBox">
                    <select class="select">
                        <option value="5" selected>每页显示05条</option>
                        <option value="10">每页显示10条</option>
                        <option value="15">每页显示15条</option>
                        <option value="20">每页显示20条</option>
                    </select>
                </div>
                <input type="reset" class="resetBtn" value="重置">
            </div>
        </form>
        <div class="gradeList">
            <table>
                <thead>
                    <th>编号</th>
                    <th>姓名</th>
                    <th>班级</th>
                    <th>语文</th>
                    <th>数学</th>
                    <th>英语</th>
                    <th>总分</th>
                    <th>编辑</th>
                    <th>删除</th>
                </thead>
                <tbody>
                    <!-- <tr>
                        <td>01_01</td>
                        <td>02_02</td>
                        <td>03_03</td>
                        <td>04_04</td>
                        <td>05_05</td>
                        <td>06_06</td>
                        <td>07_07</td>
                        <td><a href="javascript:;" class="edit">编辑</a></td>
                        <td><a href="javascript:;" class="delete">删除</a></td>
                    </tr>
                    <tr>
                        <td>01_01</td>
                        <td>02_02</td>
                        <td>03_03</td>
                        <td>04_04</td>
                        <td>05_05</td>
                        <td>06_06</td>
                        <td>07_07</td>
                        <td><a href="javascript:;" class="edit">编辑</a></td>
                        <td><a href="javascript:;" class="delete">删除</a></td>
                    </tr> -->
                </tbody>
            </table>
        </div>
        <div class="pageBox">
            <button class="prev">上一页</button>
            <span class="pageTips">第1页</span>
            <button class="next">下一页</button>
        </div>
    </div>
    <div class="shadow">
        <form action="" onsubmit="return false">
            <p><label for="">编号</label><input name="id" disabled type="text"></p>
            <p><label for="">姓名</label><input name="name" disabled type="text"></p>
            <p><label for="">班级</label><input name="class" disabled type="text"></p>
            <p><label for="">语文</label><input name="chinese" type="text"></p>
            <p><label for="">数学</label><input name="math" type="text"></p>
            <p><label for="">英语</label><input name="english" type="text"></p>
            <p>
                <input name="subBtn" type="submit" value="确定">
                <input name="retBtn" type="button" value="取消">
            </p>
        </form>
    </div>
</body>
<script>

    // 主页新增 hello


    // alert(1111);

    // 标识用户身份
    // 1. 如果用户没有登录(没有存cookie )  => 提示  <a href="./login.html">你好,请登录</a>
    // 2. 如果用户登录(存cookie => user)  => a   <a href="javascript:;">欢迎,xxx</a>

    var box = document.getElementsByClassName("box")[0];
    var tbody = document.querySelector(".gradeList table tbody");
    var searchCon = document.getElementsByClassName("searchCon")[0];
    var searchBtn = document.getElementsByClassName("searchBtn")[0];

    var orderColList = document.getElementsByClassName("orderCol");
    var orderTypeList = document.getElementsByClassName("orderType");

    var resetBtn = document.getElementsByClassName("resetBtn")[0];

    var prev = document.getElementsByClassName("prev")[0];
    var next = document.getElementsByClassName("next")[0];
    var pageTips = document.getElementsByClassName("pageTips")[0];

    var selectInp = document.getElementsByClassName("select")[0];

    var editList = document.getElementsByClassName("edit");
    var deleteList = document.getElementsByClassName("delete");

    var shadow = document.getElementsByClassName("shadow")[0];

    var form = document.querySelector(".shadow form");



    if (getCookie("logUser")) {
        var user = getCookie("logUser");
        box.innerHTML = `<a href="javascript:;">欢迎,${user}</a><button class="exit">退出</button>`;

        var button = document.getElementsByClassName("exit")[0];
        button.onclick = function () {
            setCookie("logUser", "", -1);
            location.reload();
        }
    }


    // 提取全局变量  用于记录 key orderCol orderType
    var key = "";   // 默认 ""  =>查找所有数据
    var orderCol = "id";   // 默认 "id" 排序
    var orderType = "asc"; // 默认 升序

    var showNum = 5;    // 默认每页显示5条 
    var pageIndex = 1; // 默认页码


    getData(); // 页面加载时 默认查询所有数据  =>动态生成

    tbody.onclick = function (e) {
        var e = e || window.event;
        var target = e.target || e.srcElement;

        if (target.className == "edit") {
            shadow.style.display = "block";
            var tr = target.parentElement.parentElement;
            var id = tr.getAttribute("data-id");
            // console.log(id);

            $.ajax({
                url: "../php/searchGradeById.php",
                data: {
                    id,
                },
                dataType: "json",
                success(result) {
                    var { id, name, class: cls, chinese, math, english } = result;
                    form.id.value = id;
                    form.name.value = name;
                    form.class.value = cls;
                    form.chinese.value = chinese;
                    form.math.value = math;
                    form.english.value = english;
                }
            })

            // var xhr = new XMLHttpRequest();

            // xhr.open("get", "../php/searchGradeById.php?id=" + id, true);

            // xhr.send();

            // xhr.onreadystatechange = function () {
            //     if (xhr.readyState == 4 && xhr.status == 200) {
            //         var result = JSON.parse(xhr.responseText);
            //         console.log(result);

            //         var { id, name, class: cls, chinese, math, english } = result;

            //         form.id.value = id;
            //         form.name.value = name;
            //         form.class.value = cls;
            //         form.chinese.value = chinese;
            //         form.math.value = math;
            //         form.english.value = english;


            //     }
            // }


        }

        if (target.className == "delete") {
            var tr = target.parentElement.parentElement;
            var id = tr.getAttribute("data-id");
            if (confirm("是否删除该数据")) {

                $.ajax({
                    type: "get",
                    url: "../php/deleteGradeById.php",
                    data: { id: id },
                    dataType: "json",
                    success(result) {
                        if (result.status) {
                            alert("删除成功");
                            getData();
                        } else {
                            alert(result.msg);
                        }
                    }

                });
                // var xhr = new XMLHttpRequest();

                // xhr.open("get", "../php/deleteGradeById.php?id=" + id, true);

                // xhr.send();

                // xhr.onreadystatechange = function () {
                //     if (xhr.readyState == 4 && xhr.status == 200) {
                //         var result = JSON.parse(xhr.responseText);
                //         console.log(result);

                // if (result.status) {
                //     alert("删除成功");
                //     getData();
                // } else {
                //     alert(result.msg);
                // }


                //     }
                // }
            }

        }
    }


    form.subBtn.onclick = function () {
        var id = form.id.value;
        var chinese = form.chinese.value;
        var math = form.math.value;
        var english = form.english.value;

        $.ajax({
            url: "../php/updateGradeById.php",
            data: {
                id, chinese, math, english
            },
            dataType: "json",
            success(result) {
                if (result.status) {
                    shadow.style.display = "none";
                    getData();
                } else {
                    console.log(result.msg);
                }
            }
        })


        // var xhr = new XMLHttpRequest();

        // xhr.open("get", "../php/updateGradeById.php?id=" + id + "&chinese=" + chinese + "&math=" + math + "&english=" + english, true);

        // xhr.send();

        // xhr.onreadystatechange = function () {
        //     if (xhr.readyState == 4 && xhr.status == 200) {
        //         var result = JSON.parse(xhr.responseText);
        //         console.log(result);

        //         if (result.status) {
        //             shadow.style.display = "none";
        //             getData();
        //         }

        //     }
        // }

    }

    form.retBtn.onclick = function () {
        shadow.style.display = "none";
    }





    // 分页功能
    // 1. 前端分页    数据比较少的时候,需要频繁切换时 => 前端分页
    // 原理 利用数组的slice方法裁切数据
    // 第1页  [0,5)
    // 第2页  [5,10)
    // 第3页  [10,15)

    // 第pageIndex页    [(pageIndex-1)*showNum,pageIndex*showNum)

    // 遇到的细节
    // a. 页码 ++  / -- 会超出临界值 (限定临界值)
    // b. 显示页面(showNum)切换时 也会超出最大值
    //    (1)  每次切换   重置页码  pageIndex = 1
    //    (2)  每次切换   保留页码  => 如果页码超出最大值 => 改为最大值


    // 优点
    // a. 页码切换时 没有重复进行ajax请求  页面渲染速度比较快


    // 2. 后端分页  => 数据比较庞大的时候,后端分页

    // limit m,n
    // 第1页  [0,5]
    // 第2页  [5,5]
    // 第3页  [10,5]

    // 第pageIndex页   (pageIndex-1)*showNum  showNum;



    searchBtn.onclick = searchCon.oninput = function () {
        key = searchCon.value;
        getData();
    }

    for (let i = 0; i < orderColList.length; i++) {
        let item = orderColList[i];
        item.onclick = function () {
            orderCol = this.value;
            console.log(orderCol);

            getData();
        }
    }

    for (let i = 0; i < orderTypeList.length; i++) {
        let item = orderTypeList[i];
        item.onclick = function () {
            orderType = this.value;
            console.log(orderType);

            getData();
        }
    }

    resetBtn.onclick = function () {
        key = "";   // 默认 ""  =>查找所有数据
        orderCol = "id";   // 默认 "id" 排序
        orderType = "asc"; // 默认 升序
        getData(); // 页面加载时 默认查询所有数据
    }

    selectInp.onchange = function () {
        // pageIndex = 1;   //每次切换重置页码
        showNum = this.value * 1;
        getData();
    }


    function getData() {
        $.ajax({
            type: "get",
            url: "../php/searchGrades.php",
            data: {
                key,
                orderCol,
                orderType,
                pageIndex,
                showNum,
            },
            dataType: "json",
            success(result) {

                var { maxPage, list, currentPage } = result;

                // 每次切换   保留页码  => 如果页码超出最大值 => 改为最大值
                pageIndex = pageIndex > maxPage && maxPage != 0 ? maxPage : pageIndex;
                pageTips.textContent = `第${pageIndex}页`;
                // console.log(pageIndex, currentPage);

                // pageIndex = currentPage;
                // pageTips.textContent = `第${pageIndex}页`;

                var html = "";
                list.forEach(function (item) {
                    // console.log(item);
                    // var id = item.id;
                    // var name = item.name;

                    var { id, name, class: cls, chinese, math, english, total } = item;

                    html += `<tr data-id=${id}>
                    <td>${id}</td>
                    <td>${name}</td>
                    <td>${cls}</td>
                    <td>${parseFloat(chinese)}</td>
                    <td>${parseFloat(math)}</td>
                    <td>${parseFloat(english)}</td>
                    <td>${parseFloat(total)}</td>
                    <td><a href="javascript:;" class="edit">编辑</a></td>
                    <td><a href="javascript:;" class="delete">删除</a></td>
                </tr>`;
                })
                tbody.innerHTML = html;

                prev.onclick = function () {
                    pageIndex--;
                    if (pageIndex < 1) {
                        pageIndex = 1;
                        return false;
                    }
                    getData();
                }

                next.onclick = function () {

                    //  后端虽然有maxPage 但是前端不知道,无法限制页码临界值
                    pageIndex++;
                    if (pageIndex > maxPage) {
                        pageIndex = maxPage;
                        return false;
                    }
                    getData();
                }
            }
        })
    }

    // 原本的封装
    // function getData() {



    //     // 页面加载时动态生成
    //     var xhr = new XMLHttpRequest();

    //     xhr.open("get", "../php/searchGrades.php?key=" + key + "&orderCol=" + orderCol + "&orderType=" + orderType + "&pageIndex=" + pageIndex + "&showNum=" + showNum, true);

    //     xhr.send();

    //     xhr.onreadystatechange = function () {
    //         if (xhr.readyState == 4 && xhr.status == 200) {
    //             var result = JSON.parse(xhr.responseText);
    //             // console.log(result);

    //             var { maxPage, list, currentPage } = result;

    //             // 每次切换   保留页码  => 如果页码超出最大值 => 改为最大值
    //             pageIndex = pageIndex > maxPage && maxPage != 0 ? maxPage : pageIndex;
    //             pageTips.textContent = `第${pageIndex}页`;
    //             // console.log(pageIndex, currentPage);

    //             // pageIndex = currentPage;
    //             // pageTips.textContent = `第${pageIndex}页`;

    //             var html = "";
    //             list.forEach(function (item) {
    //                 // console.log(item);
    //                 // var id = item.id;
    //                 // var name = item.name;

    //                 var { id, name, class: cls, chinese, math, english, total } = item;

    //                 html += `<tr data-id=${id}>
    //                 <td>${id}</td>
    //                 <td>${name}</td>
    //                 <td>${cls}</td>
    //                 <td>${parseFloat(chinese)}</td>
    //                 <td>${parseFloat(math)}</td>
    //                 <td>${parseFloat(english)}</td>
    //                 <td>${parseFloat(total)}</td>
    //                 <td><a href="javascript:;" class="edit">编辑</a></td>
    //                 <td><a href="javascript:;" class="delete">删除</a></td>
    //             </tr>`;
    //             })
    //             tbody.innerHTML = html;

    //             prev.onclick = function () {
    //                 pageIndex--;
    //                 if (pageIndex < 1) {
    //                     pageIndex = 1;
    //                     return false;
    //                 }
    //                 getData();
    //             }

    //             next.onclick = function () {

    //                 //  后端虽然有maxPage 但是前端不知道,无法限制页码临界值
    //                 pageIndex++;
    //                 if (pageIndex > maxPage) {
    //                     pageIndex = maxPage;
    //                     return false;
    //                 }
    //                 getData();
    //             }


    //             // // 先 生成  在获取元素 在绑定事件
    //             // for (let i = 0; i < editList.length; i++) {
    //             //     let edit = editList[i];
    //             //     edit.onclick = function () {
    //             //         console.log(this, i);
    //             //     }
    //             // }

    //             // for (let i = 0; i < deleteList.length; i++) {
    //             //     let del = deleteList[i];
    //             //     del.onclick = function () {
    //             //         console.log(this, i);
    //             //     }
    //             // }



    //         }
    //     }
    // }


    function render(list) {
        var html = "";
        list.forEach(function (item) {
            // console.log(item);
            // var id = item.id;
            // var name = item.name;

            var { id, name, class: cls, chinese, math, english, total } = item;

            html += `<tr>
                <td>${id}</td>
                <td>${name}</td>
                <td>${cls}</td>
                <td>${parseFloat(chinese)}</td>
                <td>${parseFloat(math)}</td>
                <td>${parseFloat(english)}</td>
                <td>${parseFloat(total)}</td>
                <td><a href="javascript:;" class="edit">编辑</a></td>
                <td><a href="javascript:;" class="delete">删除</a></td>
            </tr>`;
        })
        tbody.innerHTML = html;
    }

</script>

</html>